package example.echo;

import java.nio.ByteBuffer; 

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class EchoClientHander extends SimpleChannelInboundHandler<Object> {

	ByteBuf content;

	public EchoClientHander() {
		content = Unpooled.buffer(EchoClient.SIZE);
		for (int i = 0; i < content.capacity(); i++) {
			content.writeByte(i);
		}
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("read0");
		ctx.write(msg);
		System.out.println("client read0 :"  +((ByteBuf)msg).toString(CharsetUtil.UTF_8));
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("active");
		// Initialize the message.
	
		// send the message.
		ctx.writeAndFlush(content);

	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		
		System.out.println("conn inactive");
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// Close the connection when an exception is raised.
		cause.printStackTrace();
		ctx.close();
	}

}
